package indi.walty.dl8888_dirver.dirver;

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

import javax.imageio.ImageIO;

import indi.walty.dl8888_dirver.Config;

public class PrnBuilder {
	private final static byte[] BITMAP_BYTE = {(byte)0x80,(byte)0x40,(byte)0x20,(byte)0x10,(byte)0x08,(byte)0x04,(byte)0x02,(byte)0x01};
	
	public static void strFilter(String str,ByteArrayOutputStream baos) {
		byte[] bs = str.getBytes();
		for(int i = 0 ; i < bs.length ; i++) {
			if(bs[i] == 0x0a) {
				baos.write(0x0d);
			}
			baos.write(bs[i]);
		}
	}
	private static BufferedImage zoomInImage(BufferedImage originalImage, int width, int height) {
	      BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);
	      Graphics g = newImage.getGraphics();
	      g.drawImage(originalImage, 0, 0, width, height, null);
	      g.dispose();
	      return newImage;
	   }

	public static void imgFilter(int width,int height,String path,ByteArrayOutputStream baos) throws IOException {
		File file = new File(path);  
	    BufferedImage image = ImageIO.read(file); 
	    String str = (Config.PAPER_WIDTH - width*8)/2 + "," + (Config.PAPER_HEIGHT - height*8)/2 + "," + width+","+ (height*8) +","+Config.BITMAT_MODE+",";
	    System.out.println(str);
		baos.write(str.getBytes());
		byte b = 0x00;
		BitSet bs = new BitSet(8);
	    BufferedImage grayImage = zoomInImage(image,width*8,height*8);
	    int cols = grayImage.getWidth();  
	    int rows = grayImage.getHeight(); 
	    for(int row = 0 ; row < rows ; row++){  
	        for(int col = 0 ; col < cols; col++){
		        if(grayImage.getRGB(col, row) == -1) {
		        	b = (byte)(b | 0x80 >> (col%8));
				}
				if((col%8 == 7 && col != 0) || col == cols-1) {
					baos.write(b);
					b = 0x00;
				}
	        }
	        b = 0x00;
	    }  
	}
	public static List<Byte> getBytes(String path) throws IOException{
		List<Byte> list = new ArrayList();
		File file = new File(path);
		FileInputStream fis = new FileInputStream(file);
		int b = -1;
		while((b = fis.read()) != -1) {
			list.add((byte) b);
		}
		return list;
	}
	
	public static boolean buildPRN(String width,String height,String path,ByteArrayOutputStream baos) throws IOException {
		String[] s = Config.TSPL.split(Config.BYTES_PLACEHOLDER);
		strFilter(s[0],baos);
		System.out.println(s[0]);
		imgFilter(Integer.parseInt(width),Integer.parseInt(height),path,baos);
		strFilter(s[1],baos);
		System.out.println(s[1]);
		return true;
	}
	
	
}
